<?php
namespace  app\admin\model;

use think\Model;

class FinanceModel extends Model{
	protected $name = 'account';
	/**
	 * [获取信息]
	 */
	public function getInfoByWhere($where='',$is_page=false,$offset=0,$limit=20,$order='id desc'){
 		if($is_page){
 			return $this->where($where)->limit($offset, $limit)->order($order)->select();
 		}else{
 			return $this->where($where)->count();
 		}
 	}

	/**
	 * [设置流水状态]
	 */
	public function setAccStatus($id,$state){
		if($state == 1){
			$data = ['status'=>$state,'update_time'=>time(),'receivables_time'=>time(),'agent'=>session('id')];
		}else{
			$data = ['status'=>$state,'update_time'=>time(),'agent'=>session('id')];
		}
		$res = $this->where('id',$id)->update($data);
		if($res === false){
			return ['code'=>0,'msg'=>'状态更新失败'];
		}else{
			return ['code'=>1,'msg'=>'状态更新成功'];
		}
	}
	/**
	 * [添加报销单]
	 */
	public function addExpense($data){
		$this::startTrans();
		try{
			$this->save($data);
			$acc_sn = date('Ymd') . $this->id;
			$this->where('id',$this->id)->update(['account_sn'=>$acc_sn]);
			$this::commit();
			return ['code'=>1,'msg'=>'录入成功'];
		}catch(\Exception $e){
			$this::rollback();
			return ['code'=>0,'msg'=>'录入失败:'.$e->getMessage()];
		}
	}
	/**
	 * [伪删除财务流水]
	 */
	public function delAccount($idArr){
		$this::startTrans();
        try{
            foreach($idArr as $v){
                $this->where('id',$v)->update(['delete_status'=>1]);
            }
            $this::commit();
            return ['code'=>1,'msg'=>'删除成功，已放入回收站'];
        }catch(Exception $e){
            $this::rollback();
            return ['code'=>0,'msg'=>"删除失败：".$e->getMessage()];
        }
	}

	/**
	 * [恢复财务流水]
	 */
	public function AccRecovery($idArr){
		$this::startTrans();
        try{
            foreach($idArr as $v){
                $this->where('id',$v)->update(['delete_status'=>0]);
            }
            $this::commit();
            return ['code'=>1,'msg'=>'恢复成功'];
        }catch(Exception $e){
            $this::rollback();
            return ['code'=>0,'msg'=>"恢复失败：".$e->getMessage()];
        }
	}

	/**
	 * [删除财务流水]
	 */
	public function AccDelete($idArr){
		$this::startTrans();
        try{
            foreach($idArr as $v){
                $this->where('id',$v)->delete();
            }
            $this::commit();
            return ['code'=>1,'msg'=>'删除成功'];
        }catch(Exception $e){
            $this::rollback();
            return ['code'=>0,'msg'=>"删除失败：".$e->getMessage()];
        }
	}

	/**
	 * [同意/拒绝退款]
	 * 1.同意,更改流水状态status=>4
	 * 2.拒绝,更改流水状态status=>3,更改订单状态还原(-30)
	 */
	public function authAccount($id,$state){
		$res = $this->where('id',$id)->update(['status'=>$state,'update_time'=>time(),'auth'=>session('id')]);
		$state == 1 ? $msg = "同意退款" : $msg = "拒绝退款" ;
		if($res === false){
			return ['code'=>0,'msg'=>$msg.'失败'];
		}else{
			return ['code'=>1,'msg'=>$msg.'成功'];
		}
	}
}
